package cup.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import cup.core.excel.util.ExcelUtil;
import org.apache.commons.codec.Charsets;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class ExcelUtils extends ExcelUtil {

	/**
	 * 实现多 sheet 的导出
	 *
	 * @param response 响应
	 * @param fileName 文件名
	 * @param map      sheetName+ 具体数据
	 * @param clazz    实体类
	 * @param <T>
	 */
	public static <T> void export(HttpServletResponse response, String fileName, Map<String, List<T>> map, Class<T> clazz) {

		try {
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding(Charsets.UTF_8.name());
			fileName = URLEncoder.encode(fileName, Charsets.UTF_8.name());
			response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

			AtomicInteger size = new AtomicInteger(map.size());
			map.forEach((k, v) -> {
				WriteSheet writeSheet = EasyExcel.writerSheet(size.getAndDecrement(), k).head(clazz).build();
				excelWriter.write(v, writeSheet);
			});
			excelWriter.finish();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
